package com.headFirstModel.observerPattern.custom;

import java.util.ArrayList;
import java.util.List;

/**
 * 气象站：发布气象信息
 */
public class WeatherData implements Subject{
    //保存已经注册的观察者
    private List<Observer> observers;
    private float temperature; //温度
    private float humidity; //湿度
    private float pressure; //气压

    public WeatherData(){
        observers=new ArrayList<Observer>();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i=observers.indexOf(observer);
        if (i>=0) observers.remove(i);
    }

    //通知所有观察者更新气象信息
    @Override
    public void notifyObservers() {
        for (Observer observer:observers
             ) {
            observer.update(temperature,humidity,pressure);
        }
    }

    public void measurementsChanged(){
        //当从气象站得到更新观测值时，我们通知观察者。
        notifyObservers();
    }

    /**
     * 设置气象信息
     */
    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
